<script>
    function loadNav() {
        switch (sort) {
            case "price_up":
                activeID = "priceSort";
                priceSortInner = "价格↑";
                priceSortLinkChioce = "price_down";
                break;
            case "price_down":
                activeID = "priceSort";
                priceSortInner = "价格↓";
                priceSortLinkChioce = "price_up";
                break;
            case "date_down":
                activeID = "newestSort";
                priceSortInner = "价格";
                priceSortLinkChioce = "price_up";
                break;
            case "null":
                activeID = "newestSort";
                break;
            default:
                break;
        }
        $(`#priceSort`).removeClass('active')
        $(`#newestSort`).removeClass('active')
        $(`#${activeID}`).addClass('active')
        $(`#priceSortLink`).html(priceSortInner)
        $(`#priceSortLink`).attr('onclick', `itemNavLink('${priceSortLinkChioce}')`)

        // price range part (itemNav)
        if (!(parseInt(min) == 0 && parseInt(max) == 999999)) {
            $("#priceMinInput").val(min);
            $("#priceMaxInput").val(max);
        } else {
            $("#priceMinInput").val("");
            $("#priceMaxInput").val("");
        }

    }
    
        

    function loadCard() {

        // get item set by url
        loadItemSet()
            // catch exception
            .catch(handleError)

    }

    function loadItemModal(itemID) {
        // get item SQL Result
        getItemSR(itemID)
            // show item in modal
            .then(showItemInModal)
            // get seller contact SQL Result
            .then(getSellerContactSR)
            // show seller contact
            .then(showSellerContactInModal)
            // catch exception
            //.catch(handleError)
    }

    function handleError(err) {
        if (!(err == 'LOAD_ALL_INFO' 
        || err == 'ITEM_NOT_RETURN')) {
            console.log('发生错误：' + err)
        }
    }

    // experimental
    function loadItemSet() {

        return new Promise((resolve, reject) => {
            // if all items were loaded, stop loading
            if (loadStart > loadedItem) {
                reject('LOAD_ALL_INFO')
                return
            } else if (!cardReturned) {
                reject('ITEM_NOT_RETURN')
                return
            }
            // load items
            cardReturned = false
            if (loadStart == 0) {
                // when reload, clear global itemSet
                G_itemSet = []
                vueCardSet.itemSet = G_itemSet
            }
            $.ajax({
                type: 'GET',
                url: '/get/item/indexSet',
                data: {
                    search: search,
                    sort: sort,
                    min: min,
                    max: max,
                    loadStart: loadStart,
                    loadLimit: loadLimit
                },
                success: (resJson) => {
                    if (!resJson.success) {
                        reject(resJson.errorInfo)
                    } else {
                        newCardSet = resJson.data.body
                        newCardCount = resJson.data.len

                        cardReturned = true
                        loadedItem += newCardCount
                        loadStart += loadLimit

                        newCardSet.forEach(item => {
                            item.CoverFileUrl = `https://xib-item-cover.oss-cn-beijing.aliyuncs.com/${item.CoverFileName}?x-oss-process=style/webp_compress`
                        });
                        // fullfill global variable storing itemSet
                        // resJson.data: itemSet SQL result
                        G_itemSet.push.apply(G_itemSet, newCardSet)
                        //Vue.set(vueCardSet, vueCardSet.itemSet, G_itemSet)
                        // show here
                        vueCardSet.itemSet = G_itemSet
                        resolve()
                    }
                }
            })
        })
    }


    // get item SQL Result
    function getItemSR(itemID) {
        return new Promise((resolve, reject) => {
            $.ajax({
                type: 'GET',
                url: '/get/item/selectedByItemID',
                data: { 'itemID': itemID },
                success: (resJson) => {
                    if (!resJson.success) {
                        reject(resJson.toString())
                    } else {
                        resolve(resJson.data.body)
                    }
                }
            })
        })
    }

    // show item in modal
    function showItemInModal(itemSR) {
        return new Promise((resolve, reject) => {
            $(".badge").css("display", "");
            $(".badge").css("font-size", "0.9rem");
            $("#itemModalCover").attr('src', `https://xib-item-cover.oss-cn-beijing.aliyuncs.com/${itemSR.CoverFileName}?x-oss-process=style/webp_compress`);
            $("#itemModalTitle").html(itemSR.ItemName);
            $("#itemModalPrice").html("￥" + itemSR.ItemPrice);
            if (!itemSR.DeliverByPost) $("#itemModalBandagePost").css("display", 'none');
            if (!itemSR.DeliverByFace) $("#itemModalBandageFace").css("display", 'none');
            if (!itemSR.DeliverNoNeed) $("#itemModalBandageNoNeed").css("display", 'none');
            $("#itemModalDescription").html(itemSR.ItemDescription);
            $("#itemModalOldNewRate").html(itemSR.ItemOldNewRate);
            $("#itemModalRemarks").html("备注：" + itemSR.Remarks);
            // 初始化卖家信息
            $("#unloginReminder").css("display", "")
            $("#launchQQ").css("display", "none")
            $("#itemModalUserQQ").css("display", "none");
            $("#itemModalUserWeChat").css("display", "none")
            resolve(itemSR)
        })
    }

    // show seller contact
    function getSellerContactSR(itemSR) {
        console.log("Here to debug")
        return new Promise((resolve, reject) => {
            $.ajax({
                type: 'GET',
                url: '/get/user/contactMethod',
                headers: { 'Authorization': `Bearer ${token}` },
                data: { 'userName': itemSR.UserName },
                success: (resJson) => {
                    //alert(resJson.toString())
                    if (!resJson.success) {
                        console.log(resJson)
                        reject(resJson.toString())
                    } else {
                        console.log(resJson)
                        console.log(resJson.data.body)
                        resolve(resJson.data.body)
                    }
                }
            })
        })

    }

    // show seller contact
    function showSellerContactInModal(userSR) {
        return new Promise((resolve, reject) => {
            // hide unlogin reminder
            $("#unloginReminder").css("display", "none")
            // QQ
            if (userSR.UserQQ != "") {
                $("#launchQQ").attr("href", `http://wpa.qq.com/msgrd?v=3&uin=${userSR.UserQQ}&site=qq&menu=yes`)
                $("#launchQQ").css("display", "")
                $("#itemModalUserQQ").html(`QQ: ${userSR.UserQQ}`);
                $("#itemModalUserQQ").css("display", "");
            }
            // WeChat
            if (userSR.UserWeChat != "") {
                $("#itemModalUserWeChat").html(`微信: ${userSR.UserWeChat}`);
                $("#itemModalUserWeChat").css("display", "");
            }
        })
    }

</script>